package com.scfire.project

import grails.transaction.Transactional;

import grails.converters.JSON
import grails.transaction.Transactional
import net.sf.json.JSONArray
import net.sf.json.JSONObject

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import com.mongodb.BasicDBObject
import com.mongodb.DBCollection
import com.mongodb.DBObject
import com.scfire.baseInfo.Gson
import com.scfire.fund.FDonate
import com.scfire.fund.FRuler
import com.scfire.security.Member
import com.scfire.util.SCFIREConstants
import com.scfire.weixin.WeiXinConstants

class SubProjectController {

	def Log LOG = LogFactory.getLog(SubProjectController.class)

	def springSecurityService
	def deviceInfoService
	def weiXinService
	def SystemMessageService
	def mongo
	def grailsApplication
	
	
	def checkFdonate(){
		
		def subprojects =SubProject.findAll();
		def db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)
		DBCollection projectCollection = db.getCollection("subProject")
		int i=0
		for(SubProject sub:subprojects){
			DBObject queryCondition= new BasicDBObject()
			queryCondition.put("_id",sub.id)
		    int subFDonates=0
			def fRuler= FRuler.findByProject(sub.project)			
			if(fRuler!=null){
				def donates = Donate.findAllBySubProject(sub.id)
				for(Donate d:donates){
					def fDonates= FDonate.findByDonate(d.id)
					if(fDonates?.donate_fee){
						subFDonates+=fDonates?.donate_fee
					}
				}
			}
			int subfdonateSize=0
			if(sub?.donates){
			  subfdonateSize = sub.donates.size()
			}
			BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("subdonateSize", subfdonateSize)
				.append("subfdonate", subFDonates))			
			projectCollection.update(queryCondition, updateParameter,true,true)
			i++
			println i+"---"+sub.id+"----"+subfdonateSize+"---"+subFDonates+"-----"
		}
		
	}
	
	

	/**
	 * 创建一起捐项目
	 * @param null
	 * @return null
	 *
	 * **/
	def create() {
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()

		Member member = (Member)user
		def projectid= params.projectid
		Project project = Project.findById(projectid)
		render view:"subcreatemb", model:[project:project,user:user]
	}
	
	def editSub(){
		def subprojectid = params.subprojectid
		def subproject =  SubProject.findById(subprojectid)
		render view:"subeditmb", model:[project:subproject.project,subproject:subproject]
		
	}

	/**
	 * 保存一起捐项目信息
	 * @param subProjectInstance
	 * @return null
	 *
	 * **/
	@Transactional
	def save(SubProject subProjectInstance) {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		def gson = new Gson()
		if (subProjectInstance == null) {
			notFound()
			return
		}
		
		def user = springSecurityService.getCurrentUser()

		def projectid = params.projectid
		Project project = Project.findById(projectid)
		Member member = (Member)user
		
		def url = WeiXinConstants.server + "/subProject/save"

		def subprojectid = params.subprojectid
		if(subprojectid!=null){//修改
			
			SubProject subproject = SubProject.findById(subprojectid)
			subproject.subdescription = params.subdescription
			subproject.updateDate = new Date()
			if(params.subamount==-1){
				subproject.subamount = -1
				subproject.subrest = project.rest
			}else{
			    subproject.subamount = Integer.parseInt(params.subamount)
				subproject.subrest = Integer.parseInt(params.subamount)
			}
			subproject.save(flush:true)
		}else{//保存
			
			subProjectInstance.createDate = subProjectInstance.createDate?subProjectInstance.createDate:new Date()
			subProjectInstance.updateDate = new Date()
			if(subProjectInstance.subamount==-1){
				subProjectInstance.subrest = project.rest
			}else{
				subProjectInstance.subrest = subProjectInstance.subamount
			}

			subProjectInstance.subprogress = 0

			subProjectInstance.project = project.id
			subProjectInstance.member = member.id
			//保存子项目
			subProjectInstance.save(flush:true)
			/*project.sbuProjectSize++;
			project.save(flush:true)*/
		}

		if(request.getQueryString()){
			url += request.getQueryString()
		}
		def shareUrl = WeiXinConstants.server + "/subProject/subProjectDetail?subprojectid="+subProjectInstance.id
		def lastDate = null
		Set<Member> donateUsers = new HashSet<Member>()
		//微信发送朋友所需要的参数
		Map map = weiXinService.jsapiTicketSign(url)
		def noncestr = map.get("noncestr")
		def jsapi_ticket = map.get("jsapi_ticket")
		def timestamp = map.get("timestamp")
		def sign = map.get("sign")
		def imgUrl =  WeiXinConstants.img_url

		imgUrl += project.img

		Date curDate = new Date()
		if(curDate>=project.endDate){
			lastDate = 0
		}else{
			lastDate = project.endDate - curDate
		}
		//捐赠人信息去重
		if(subProjectInstance.donates!=null){
			//最多查询前5个
			for(Donate d:subProjectInstance.donates){
				Member m = Member.findById(d.member)
				//donates.add(d.member)
				donateUsers.add(m)
				if(donateUsers.size()>6){
					break
				}
			}
		}
		
		def fRuler = FRuler.findByProject(project)
		def subFDonates=0
		def subMember
		if(fRuler!=null){
			if(subprojectid==null){
				
				def Donates = Donate.findAllBySubProject(subProjectInstance.id)
				for(Donate d:Donates){
					if(d?.fDonate?.donate_fee){
						subFDonates+=d?.fDonate?.donate_fee
					}
				}
			}
			else{
				
				def Donates = Donate.findAllBySubProject(subproject.id)
				for(Donate d:Donates){
					if(d?.fDonate?.donate_fee){
						subFDonates+=d?.fDonate?.donate_fee
					}
					
				}
			}
			subMember = Member.findById(subProjectInstance.member)
			if(subFDonates!=null){
				subFDonates=subFDonates/100
			}
			
		}
		withFormat {
			//跳转到详细页面
			html {
				if("pc".equals(str)){
					render view: "sharesubprojectmb", model: [subMember:subMember,subFDonates:subFDonates,user:member,subproject:subProjectInstance, project:project,lastDate:lastDate,donateUsers:donateUsers     , appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign , url : url , name : user?.nickname , imgUrl : imgUrl,shareUrl:shareUrl,fRuler:fRuler]
				}
				if("mobile".equals(str)){
					render view: "sharesubprojectmb", model: [subMember:subMember,subFDonates:subFDonates,user:member,subproject:subProjectInstance, project:project,lastDate:lastDate,donateUsers:donateUsers     ,  appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign , url : url , name : user?.nickname , imgUrl : imgUrl,shareUrl:shareUrl,fRuler:fRuler]
				}
			}
			json {

			}
		}
	}

	
	/**
	 * 异步json 格式的 一起捐列表
	 * @return
	 */
	def subProjectList(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		params.max=20
		
		
		String projectId = params.projectId
		if(projectId == null){
			notFound()
			return
		}
		
		Project project = Project.findById(projectId)
		if(project == null){
			notFound()
			return
		}
		
		def criteria = SubProject.createCriteria()
		def fc = {
			eq("project",project.id)
			order("date","desc")
		}
		
		def subProjects = criteria.list(params,fc);
		
		withFormat {
			html{
				
			}
			json {
				JSONArray subprojectList = new JSONArray()
				for(SubProject subproject:subProjects){
					JSONObject json = new JSONObject()
					json.put("headimgurl",subproject.member.headimgurl)
					json.put("nickname", subproject.member.nickname)
					json.put("amount", subproject.subamount)
					json.put("donate",subproject.subdonate)
					json.put("createDate",subproject.createDate.getMonth()+"-"+subproject.createDate.getDay()+" "+subproject.createDate.getHours()+":"+subproject.createDate.getMinutes())
					json.put("subdescription", subproject.subdescription)
					subprojectList.add(json)
				}
				render subprojectList as JSON
			}
		}
		
		//return
	}
	
	/**
	 * 子项目详细信息
	 */
	def subProjectDetail(){
		String subprojectid = params.subprojectid
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		Member member = (Member)user
		/*def roles = springSecurityService.getAuthentication()?.authorities*/

		//获取项目详细信息
		Set<Member> donateUsers = new HashSet<Member>()
		SubProject subproject = null
		Project project = null
		def lastDate = null	
		float subFDonates=0
		def fRuler
		def projectPics
		try{
			subproject = SubProject.findById(Long.valueOf(subprojectid))
			if (subproject == null) {
				notFound()
				return
			}
//			Member subProjectMember = subproject?.member
//			if(subProjectMember!=member){
//				notFound()
//				return
//			}
			member = Member.findById(subproject.member)
			project =Project.findById(subproject.project)
			projectPics = ProjectPic.findAllByProject(project.id)
			if (project == null) {
				notFound()
				return
			}
			 fRuler= FRuler.findByProject(project)

			Date curDate = new Date()
			if(curDate>=project.endDate){
				lastDate = 0
			}else{
				lastDate = project.endDate - curDate
			}
			//捐赠人信息去重
			
				//最多查询前5个
				def donates = Donate.findAllBySubProject(subproject.id)
				println donates
				if(donates){
					for(Donate d:donates){
						//donateUsers.add(d.member)
						Member m = Member.findById(d.member)
						donateUsers.add(m)
						
						if(donateUsers.size()>5){
							break
						}
					}
				}

		}catch(Exception e){
			LOG.error("Find project by projectid catch exception. "+e.getMessage())
			notFound()
			e.printStackTrace()
			return
		}

		def url = WeiXinConstants.server + "/subProject/subProjectDetail"
		if(request.getQueryString()){
			url += "?" +request.getQueryString()
		}
		def shareUrl = WeiXinConstants.server + "/subProject/subProjectDetail?subprojectid="+subproject.id
		//微信发送朋友所需要的参数
		Map map = weiXinService.jsapiTicketSign(url)
		def noncestr = map.get("noncestr")
		def jsapi_ticket = map.get("jsapi_ticket")
		def timestamp = map.get("timestamp")
		def sign = map.get("sign")
		def imgUrl =  WeiXinConstants.img_url+project.img
		
		withFormat {
			//跳转到详细页面
			html {
				if(project.verified.equals(SCFIREConstants.PROJECT_APPROVE_PASS)){
					if("pc".equals(str)){
						render view: "subprojectdetailmb", model: [subFDonates:subproject.subfdonate/100,subproject:subproject, project:project,projectPics:projectPics,lastDate:lastDate,donateUsers:donateUsers,user:member, appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign , url : url , name : user?.nickname , imgUrl : imgUrl,shareUrl:shareUrl,fRuler:fRuler]
					}
					if("mobile".equals(str)){
						render view: "subprojectdetailmb", model: [subFDonates:subproject.subfdonate/100,subproject:subproject, project:project,projectPics:projectPics,lastDate:lastDate,donateUsers:donateUsers,user:member, appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign , url : url , name : user?.nickname , imgUrl : imgUrl,shareUrl:shareUrl,fRuler:fRuler]
					}
				}
				else{
					if("pc".equals(str)){
						render view: "subdonatefinishmb", model: [subFDonates:subproject.subfdonate/100,subproject:subproject,projectPics:projectPics, project:project,lastDate:lastDate,donateUsers:donateUsers,user:member, appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign , url : url , name : user?.nickname , imgUrl : imgUrl,shareUrl:shareUrl,fRuler:fRuler]
					}
					if("mobile".equals(str)){
						render view: "subdonatefinishmb", model: [subFDonates:subproject.subfdonate/100,subproject:subproject, project:project,projectPics:projectPics,lastDate:lastDate,donateUsers:donateUsers,user:member,appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign , url : url , name : user?.nickname , imgUrl : imgUrl,shareUrl:shareUrl,fRuler:fRuler]
					}
				}
			}
			json {

			}
		}
	}

	def aftershare(){
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		Member member = (Member)user
		String subprojectid = params.subprojectid
		SubProject subproject = SubProject.findById(subprojectid)
		
		def url = WeiXinConstants.server + "/subProject/aftershare"
		
		if(subproject==null){
			notFound()
			return
		}
		
		//二次分享显示初始创建者信息
		member = subproject.member
		Project project = Project.findById(subproject.project)
		if(project==null){
			notFound()
			return
		}
		def fRuler = FRuler.findByProject(project)
		def lastDate = null
		
		Date curDate = new Date()
		if(curDate>=project.endDate){
			lastDate = 0
		}else{
			lastDate = project.endDate - curDate
		}
		
		
		Set<Member> donateUsers = new HashSet<Member>()
		if(subproject.donates!=null){
			//最多查询前5个
			for(Donate d:subproject.donates){
				Member m = Member.findById(d.member)
				//donates.add(d.member)
				donateUsers.add(m)
				if(donateUsers.size()>5){
					break
				}
			}
		}
		
		/*int subFDonates
		if(fRuler!=null){
			for(Donate d:subproject.donates){
				if(d?.fDonate?.donate_fee){
					subFDonates+=d?.fDonate?.donate_fee
				}
				
			}
			if(subFDonates!=null){
				subFDonates=subFDonates/100
			}
			
		}*/
		
		
		if(request.getQueryString()){
			url += "?" +request.getQueryString()
		}
		def shareUrl = WeiXinConstants.server + "/subProject/subProjectDetail?subprojectid="+subproject.id
		//微信发送朋友所需要的参数
		Map map = weiXinService.jsapiTicketSign(url)
		def noncestr = map.get("noncestr")
		def jsapi_ticket = map.get("jsapi_ticket")
		def timestamp = map.get("timestamp")
		def sign = map.get("sign")
		def imgUrl =  WeiXinConstants.img_url

		imgUrl += project.img
		
		render view:"aftersharemb",model:[subFDonates:subproject.subfdonate/100,subproject:subproject, project:project,lastDate:lastDate,donateUsers:donateUsers,user:member, appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign , url : url , name : user?.nickname , imgUrl : imgUrl,shareUrl:shareUrl,fRuler:fRuler]
	}

	/**
	 * 一起捐赠
	 * @param null
	 * @return null
	 *
	 * **/
	def subDonate(){
		//TODO
		//1.直接捐赠project

		//TODO
		//2.保存信息到subproject

		//TODO
		//3.捐赠donate实体保存两份数据，一份belongsTo Project 一份belongsTo subProject

		//TODO
		//4.金额计算，Project rest计算，SubProject rest计算
		println "开始支付.."
		String donateurl = "";
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		def gson = new Gson()

		Member member = (Member)springSecurityService.getCurrentUser()

		//商户订单号
		String out_trade_no = UUID.randomUUID()
		//交易状态
		String trade_status = "false"

		println "交易状态："+trade_status

		String memberid = member.id
		String projectid = params.projectid
		String subprojectid = params.subprojectid

		boolean checked;
		String checked_string = "true"
		float donate_fee = Float.parseFloat(params.donateprice)
		float operate_fee =  donate_fee*0.05
		float total_fee = donate_fee+operate_fee

		if(checked_string.equals("true")){
			checked = true
		}else{
			checked = false
		}


		println "验证成功"

		//1.直接捐赠project
		Project.withTransaction { project_status ->

			Project project = Project.findById(projectid)
			SubProject subproject

			//2.保存信息到subproject
			if(!subprojectid.equals("-1")){
				SubProject.withTransaction {subproject_status ->
					subproject = SubProject.findById(subprojectid)
					subproject.subrest -= Float.valueOf(donate_fee)
					subproject.subdonate += Float.valueOf(donate_fee)
					subproject.subprogress = 100-(subproject.subrest/subproject.subamount)*100
					//4.金额计算，subProject rest计算，
					if(subproject.subrest <= 0){
						//TODO
						subproject.subrest = 0
						subproject.subprogress = 100
					}

				}
			}

			Donate.withTransaction { donate_status ->
				Donate donate = Donate.findByOut_trade_no(out_trade_no)
				if(donate){
					render "success"
					return
				}
				println "增加捐赠记录"
				long timestap = System.currentTimeMillis()/1000
				//捐赠信息
				donate = new Donate()
				donate.donateNo = UUID.randomUUID()
				donate.donateNoNew = project.id+""+member.id+""+timestap
				donate.money = Float.valueOf(total_fee)

				//记录支付金额信息
				donate.donate_fee = donate_fee
				donate.operate_fee = operate_fee
				donate.operate_fee_status = checked

				donate.date = new Date()
				donate.status = true
				donate.member = member
				//3.捐赠donate实体保存两份数据，一份belongsTo Project 一份belongsTo subProject
				donate.project = project
				if(!subprojectid.equals("-1")) donate.subProject = subproject
				donate.out_trade_no = out_trade_no
				donate.openid = member?.openid
				donate.transaction_id = ""
				donate.attach = projectid+"#"+memberid+"#"+checked_string+"#"+donate_fee+"#"+operate_fee
				donate.type = "支付宝支付"
				donate.save()
			}

			if(!subprojectid.equals("-1")) subproject.save(flush:true)
			//4.金额计算，Project rest计算，    不包含平台管理费
			project.rest -= Float.valueOf(donate_fee)

			project.progress = 100-(project.rest/project.amount)*100
			//将剩余的钱捐入某个永久项目
			if(project.rest <= 0){
				//TODO
				project.rest = 0
				project.progress = 100
				project.verified = SCFIREConstants.PROJECT_APPROVE_EXECUTE
				//保存系统通知消息
				SystemMessageService.sendSysMessage(SCFIREConstants.SYSTEM_MESSAGE_PROJECT_FUND_SUCCESS_FRONT+project.name+SCFIREConstants.SYSTEM_MESSAGE_PROJECT_FUND_SUCCESS_BACK, project.member)
			}
			//捐赠用户去重
			Set donateMember = new HashSet<>()
			donateMember.add(member.id)
			for(Donate d:project.donates){
				def m = d.member.id
				donateMember.add(m)
			}
			//捐赠的用户数累加，按照捐一次累积一次，不做member的去重
			project.donateNum = project.donateNum+1
			if(!project.save(flush:true)){
				project.errors.each { println it }
			}

		}//project.withTransaction }
		render "success"	//请不要修改或删除
		return



	}



	/**
	 * 一起捐赠
	 * @param null
	 * @return null
	 *
	 * **/
	def subList(){
		//TODO
		//显示一起捐列表信息
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		//共捐赠金额
		def totalMoney=0
		Member member = (Member) user
		def Criteria = SubProject.createCriteria()
		def filterClosure = {
			order("createDate","desc")
			eq("member",member.id)
		}
		params.max  = 10
		//所有子项目
		List<SubProject> subprojectsTotal = Criteria.list(filterClosure)
		def subprojectsNum = subprojectsTotal.size()
		//部分offset项目
		List<SubProject> subprojects = Criteria.list(params,filterClosure)
        int donateNum=0
		//捐赠用户去重
		for(SubProject subproject :subprojectsTotal){
			totalMoney+= subproject.subdonate
			for(Donate d:subproject.donates){
				donateNum++
			}
		}
		
		withFormat {
			//跳转到详细页面
			html {
				if("pc".equals(str)){
					render view: "sublistmb", model: [subprojects:subprojects,donateNum:donateNum,subprojectsNum:subprojectsNum,totalMoney:totalMoney]
				}
				if("mobile".equals(str)){
					render view: "sublistmb", model: [subprojects:subprojects,donateNum:donateNum,subprojectsNum:subprojectsNum,totalMoney:totalMoney]
				}
			}
			json {

				JSONArray subjson = new JSONArray()
				for(SubProject subproject:subprojects){
					
					JSONObject json = new JSONObject()
					def project = Project.findById(subproject.project)
					def donateSize = Donate.countBySubProject(subproject.id)
					json.put("subprojectid",subproject.id)
					json.put("name",project.name)
					json.put("img",project.img)
					json.put("subamount",subproject.subamount)
					json.put("subdonate",subproject.subdonate)
					json.put("donatenums",donateSize)
					json.put("subprogress",subproject.subprogress)
					subjson.add(json)
					
				}
				render subjson as JSON
				
			}
		}
	}

	/**
	 * 项目信息未找到
	 * @param null
	 * @return null
	 *
	 * **/
	protected void notFound() {
		def gson = new Gson()
		withFormat {
			html {
				flash.message = "未找到该项目！"
				redirect (controller: "errors", action: "notFound")
			}
			json {
				gson.setResult(false)
				gson.setCode(404)
				gson.setInfo(["text": "未找到该项目！"])
				render gson as JSON
			}
		}
	}
}
